<template>
  <div class="list">
    <van-pull-refresh success-duration="1500" :success-text="tipText" v-model="isLoading" @refresh="onRefresh">
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      :error.sync="error"
      error-text="请求失败，点击重新加载"
      @load="onLoad"
    >
      <article-item :row="item" v-for="item in list" :key="item.art_id+''" >
      </article-item>
    </van-list>
  </van-pull-refresh>
  </div>
</template>

<script>
import { getArticles } from '@/api/news.js'
import ArticleItem from '@/components/ArticleItem.vue'
export default {
  name: 'ArticleList',
  components: { ArticleItem },
  props: {
    channel_id: {
      type: Number,
      required: true
    }
  },

  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      error: false,
      timestamp: Date.now(),
      isLoading: false,
      tipText: ''
    }
  },

  created () {},

  methods: {
    async onLoad () {
      // 异步更新数据
      try {
        const res = await getArticles({
          channel_id: this.channel_id,
          timestamp: this.timestamp,
          with_top: 1
        })
        this.list.push(...res.results)
        this.timestamp = res.pre_timestamp
        this.loading = false
        if (!res.results) {
          this.finished = true
        }
      } catch (err) {
        this.loading = false
        this.error = true
      }
    },
    async onRefresh () {
      try {
        const res = await getArticles({
          channel_id: this.channel_id,
          timestamp: this.timestamp,
          with_top: 1
        })
        if (Math.random() > 0.5) {
          console.lg(2)
        }
        this.list.unshift(...res.results)
        this.isLoading = false
        this.tipText = '刷新成功'
      } catch (err) {
        this.isLoading = false
        this.tipText = '刷新失败'
      }
    }
  }
}
</script>

<style scoped lang="less">
.list{
  height: 80vh;
  overflow-y: scroll;
}
</style>
